package com.itjin.health.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.health.common.BaseResponse;
import com.itjin.health.common.ResultUtils;
import com.itjin.health.domain.dto.rehabilitation.RehabilitationPlanAddRequest;
import com.itjin.health.domain.dto.rehabilitation.RehabilitationPlanProgressUpdateRequest;
import com.itjin.health.domain.dto.rehabilitation.RehabilitationPlanUpdateRequest;
import com.itjin.health.domain.vo.RehabilitationPlanDetailVO;
import com.itjin.health.domain.vo.RehabilitationPlanVO;
import com.itjin.health.exception.BusinessException;
import com.itjin.health.exception.ErrorCode;
import com.itjin.health.service.RehabilitationPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/rehabilitation")
@Api(tags = "康复计划接口")
@Slf4j
public class RehabilitationController {

  @Resource
  private RehabilitationPlanService rehabilitationPlanService;

  /**
   * 添加康复计划
   * 
   * @param rehabilitationPlanAddRequest 康复计划添加请求
   * @param request                      HTTP请求
   * @return 添加结果
   */
  @PostMapping("/add")
  @ApiOperation(value = "添加康复计划", notes = "需要理疗师权限")
  public BaseResponse<Integer> addRehabilitationPlan(
      @RequestBody RehabilitationPlanAddRequest rehabilitationPlanAddRequest,
      HttpServletRequest request) {
    // 获取当前登录用户ID
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    // 获取角色
    String userRole = (String) request.getSession().getAttribute("userRole");
    if (!"管理员".equals(userRole) && !"教师".equals(userRole) && !"超级管理员".equals(userRole)) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无理疗师权限");
    }

    Integer result = rehabilitationPlanService.addRehabilitationPlan(rehabilitationPlanAddRequest, userId);
    return ResultUtils.success(result);
  }

  /**
   * 更新康复计划
   * 
   * @param rehabilitationPlanUpdateRequest 康复计划更新请求
   * @param request                         HTTP请求
   * @return 更新结果
   */
  @PostMapping("/update")
  @ApiOperation(value = "更新康复计划", notes = "需要理疗师权限")
  public BaseResponse<Boolean> updateRehabilitationPlan(
      @RequestBody RehabilitationPlanUpdateRequest rehabilitationPlanUpdateRequest,
      HttpServletRequest request) {
    // 获取当前登录用户ID
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    // 获取角色
    String userRole = (String) request.getSession().getAttribute("userRole");
    if (!"管理员".equals(userRole) && !"教师".equals(userRole) && !"超级管理员".equals(userRole)) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无理疗师权限");
    }

    Boolean result = rehabilitationPlanService.updateRehabilitationPlan(rehabilitationPlanUpdateRequest, userId);
    return ResultUtils.success(result);
  }

  /**
   * 更新康复计划进度
   * 
   * @param progressUpdateRequest 进度更新请求
   * @param request               HTTP请求
   * @return 更新结果
   */
  @PostMapping("/progress/update")
  @ApiOperation(value = "更新康复计划进度", notes = "理疗师和患者均可更新")
  public BaseResponse<Boolean> updateProgress(
      @RequestBody RehabilitationPlanProgressUpdateRequest progressUpdateRequest,
      HttpServletRequest request) {
    // 获取当前登录用户ID
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    Boolean result = rehabilitationPlanService.updateProgress(progressUpdateRequest, userId);
    return ResultUtils.success(result);
  }

  /**
   * 获取康复计划详情
   * 
   * @param id      康复计划ID
   * @param request HTTP请求
   * @return 康复计划详情
   */
  @GetMapping("/get")
  @ApiOperation(value = "获取康复计划详情")
  public BaseResponse<RehabilitationPlanDetailVO> getRehabilitationPlanById(
      @ApiParam(value = "康复计划ID", required = true) @RequestParam Integer id,
      HttpServletRequest request) {
    // 获取当前登录用户ID
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    RehabilitationPlanDetailVO result = rehabilitationPlanService.getRehabilitationPlanDetailById(id);
    return ResultUtils.success(result);
  }

  /**
   * 获取理疗师创建的康复计划列表
   * 
   * @param page     页码
   * @param pageSize 每页大小
   * @param keyword  关键词
   * @param status   状态
   * @param request  HTTP请求
   * @return 分页结果
   */
  @GetMapping("/list/therapist")
  @ApiOperation(value = "获取理疗师创建的康复计划列表", notes = "需要理疗师权限")
  public BaseResponse<Page<RehabilitationPlanVO>> getRehabilitationPlanListByTherapist(
      @ApiParam(value = "页码", required = true) @RequestParam Integer page,
      @ApiParam(value = "每页大小", required = true) @RequestParam Integer pageSize,
      @ApiParam(value = "关键词") @RequestParam(required = false) String keyword,
      @ApiParam(value = "状态") @RequestParam(required = false) Integer status,
      HttpServletRequest request) {
    // 获取当前登录用户ID
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    // 获取角色
    String userRole = (String) request.getSession().getAttribute("userRole");
    if (!"管理员".equals(userRole) && !"教师".equals(userRole) && !"超级管理员".equals(userRole)) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无理疗师权限");
    }

    Page<RehabilitationPlanVO> result = rehabilitationPlanService.getRehabilitationPlanListByTherapist(
        userId, page, pageSize, keyword, status);
    return ResultUtils.success(result);
  }

  /**
   * 获取患者的康复计划列表
   * 
   * @param page     页码
   * @param pageSize 每页大小
   * @param keyword  关键词
   * @param status   状态
   * @param request  HTTP请求
   * @return 分页结果
   */
  @GetMapping("/list/patient")
  @ApiOperation(value = "获取患者的康复计划列表", notes = "学生查看自己的康复计划")
  public BaseResponse<Page<RehabilitationPlanVO>> getRehabilitationPlanListByPatient(
      @ApiParam(value = "页码", required = true) @RequestParam Integer page,
      @ApiParam(value = "每页大小", required = true) @RequestParam Integer pageSize,
      @ApiParam(value = "关键词") @RequestParam(required = false) String keyword,
      @ApiParam(value = "状态") @RequestParam(required = false) Integer status,
      HttpServletRequest request) {
    // 获取当前登录用户ID
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    // 学生角色只能查看自己的康复计划
    String userRole = (String) request.getSession().getAttribute("userRole");
    if ("学生".equals(userRole)) {
      Page<RehabilitationPlanVO> result = rehabilitationPlanService.getRehabilitationPlanListByPatient(
          userId, page, pageSize, keyword, status);
      return ResultUtils.success(result);
    }

    // 管理员/理疗师需要指定患者ID才能查看
    Integer patientId = request.getParameter("patientId") != null ? Integer.parseInt(request.getParameter("patientId"))
        : null;
    if (patientId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "管理员/理疗师查看需要指定患者ID");
    }

    Page<RehabilitationPlanVO> result = rehabilitationPlanService.getRehabilitationPlanListByPatient(
        patientId, page, pageSize, keyword, status);
    return ResultUtils.success(result);
  }

  /**
   * 获取与伤病报告关联的康复计划
   * 
   * @param injuryReportId 伤病报告ID
   * @param request        HTTP请求
   * @return 康复计划列表
   */
  @GetMapping("/list/injury")
  @ApiOperation(value = "获取与伤病报告关联的康复计划")
  public BaseResponse<List<RehabilitationPlanVO>> getRehabilitationPlansByInjuryReportId(
      @ApiParam(value = "伤病报告ID", required = true) @RequestParam Integer injuryReportId,
      HttpServletRequest request) {
    // 获取当前登录用户ID
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    List<RehabilitationPlanVO> result = rehabilitationPlanService
        .getRehabilitationPlansByInjuryReportId(injuryReportId);
    return ResultUtils.success(result);
  }
}
